package com.liu.activiti.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.activiti.enums.HttpStateEnum;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Component
public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException)
            throws IOException {
        // 返回 401 状态码和错误信息
        // 设置响应状态码
        response.setStatus(HttpStateEnum.TOKENERROR.getCode());
        response.setContentType("application/json");

        // 创建返回的 JSON 信息
        Map<String, Object> responseBody = new HashMap<>();
        responseBody.put("status", HttpStateEnum.TOKENERROR.getCode());
        // 尝试获取自定义异常信息
        // 这里可以尝试直接访问 authException 的消息
        responseBody.put("message", HttpStateEnum.TOKENERROR.getMessages());

        // 将 JSON 写入响应体
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(responseBody);
        out.print(json);
        out.flush();
    }
}
